package com.vinaprime.primeschedule.presentation;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SearchView;
import android.widget.SearchView.OnCloseListener;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;

import com.vinaprime.primeschedule.businesslayer.VPProject_BL;
import com.vinaprime.primeschedule.entities.VPProject;

public class VpprojectExpandableActivity extends Activity{
	public final static String PROJECT_SENT_DETAIL = "com.vinaprime.primeschedule.presentation.PROJECT_SENT_DETAIL";
	
	private List<VPProject> mProjcetGroupList;
    private List<VPProject> mProjectList;
    private Map<VPProject, List<VPProject>> mProjectCollection;
    private SearchView mSearchView;
    private EditText mTxtSearch;
    private ExpandableListView mExpListView;
    private ExpandableListProjectAdapter mExpListAdapter;
    
    private VPProject mProject;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vpproject_expandable);
		ActionBar actionBar = getActionBar();
		Drawable d=getResources().getDrawable(R.drawable.background_top_shape_green);
		actionBar.setBackgroundDrawable(d);
		
		mProject = new VPProject();
		
		try {
			createInfo();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
		mExpListAdapter = new ExpandableListProjectAdapter(
                this, this.mProjcetGroupList, this.mProjectCollection);
		mExpListView = (ExpandableListView) findViewById(R.id.expProjectList);
		mExpListView.setEnabled(true);
		mExpListView.setAdapter(mExpListAdapter);
        
        registerForContextMenu(mExpListView);
        
        mExpListView.setOnChildClickListener(new OnChildClickListener() {
       	 
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {
            	
            	mProject = (VPProject) mExpListAdapter.getChild(groupPosition, childPosition);
                
                Intent mIntent = new Intent(getApplicationContext(), VpprojectDetailActivity.class);
                mIntent.putExtra(PROJECT_SENT_DETAIL, new String[] {"VIEW", String.valueOf(mProject.getVppId())});
                startActivity(mIntent);
 
                return true;
            }
        });
        
        //Create Menu Search
        ActionBar myActionBar = getActionBar();
    	myActionBar.setCustomView(R.layout.activity_filter_search_view);
    	myActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
    	
    	SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		mSearchView = (SearchView) findViewById(R.id.searchViewFilter);
		mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
		//mSearchView.setFocusableInTouchMode(true);
		mSearchView.setIconifiedByDefault(true);
		//mSearchView.setVisibility(View.INVISIBLE);
		mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
			
			@Override
			public boolean onQueryTextSubmit(String query) {
				// TODO Auto-generated method stub
				mExpListAdapter.filterData(query);
				expandAll();
				
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String newText) {
				// TODO Auto-generated method stub
				mExpListAdapter.filterData(newText);
				expandAll();
				
				return false;
			}
		});
		
		mSearchView.setOnCloseListener(new OnCloseListener() {
			
			@Override
			public boolean onClose() {
				// TODO Auto-generated method stub
				mExpListAdapter.filterData("");
				expandAll();
				
				return false;
			}
		});
	}

	@Override 
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.vpproject_expandable, menu);
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    
	    case R.id.action_add:
	    	Intent myIntent = new Intent(this, VpprojectDetailActivity.class);
	    	myIntent.putExtra(PROJECT_SENT_DETAIL, new String[] {"ADD", "NO_ID"});
	    	startActivity(myIntent);
	    default:
	    	break;
	    }
		return true;
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			 ContextMenuInfo menuInfo) {
			 // TODO Auto-generated method stub
			
			ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuInfo;

		    int type = ExpandableListView.getPackedPositionType(info.packedPosition);
		    
		    if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD)
		    {
		    	super.onCreateContextMenu(menu, v, menuInfo);
				 getMenuInflater()
				 .inflate(R.menu.vpproject_context, menu);
				 menu.setHeaderTitle(R.string.ctx_action_title);
		    }
	 }
	 
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();

        int type = ExpandableListView.getPackedPositionType(info.packedPosition);
        
        if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
            final int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); 
            final int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
            
            mProject = (VPProject) mExpListAdapter.getChild(groupPos, childPos);
            
            //Toast.makeText(this, "AAA" + ": Child " + childPos + " clicked in group " + groupPos, Toast.LENGTH_SHORT).show();
            
            switch(item.getItemId())
    		{
    			case R.id.ctm_edit:
    				Intent intent = new Intent(getApplicationContext(), VpprojectDetailActivity.class);
    				intent.putExtra(PROJECT_SENT_DETAIL, new String[] {"EDIT", String.valueOf(mProject.getVppId())});
    				startActivity(intent);
    				
    				break;
    			case R.id.ctm_delete:				   
    				AlertDialog.Builder builder = new AlertDialog.Builder(this);
    				builder.setTitle(R.string.alt_title_question);
    				builder.setIcon(android.R.drawable.ic_dialog_alert);
                    builder.setMessage("Do you want to remove?");
                    builder.setCancelable(false);
                    builder.setPositiveButton("Yes",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                	Toast.makeText(getApplicationContext(), "group: " + groupPos + ", child: " + childPos, Toast.LENGTH_SHORT).show();
                                	System.out.println("group: " + groupPos + ", child: " + childPos);
                                	//List<VPProject> child = mProjectCollection.get(mProjcetListName.get(childPos));
                                	//child.remove(childPos);
                                	mExpListAdapter.removeChild(groupPos, childPos);
                                    mExpListAdapter.notifyDataSetChanged();
                                	ApplicationInformation appInfo = new ApplicationInformation(getApplicationContext());
                    				String path = appInfo.getDBPath();
                    				VPProject_BL projectBL = new VPProject_BL(getApplicationContext(), path);
                    				projectBL.deleteProject(mProject.getVppId());
                    				
                                	
                                }
                            });
                    builder.setNegativeButton("No",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });
                    AlertDialog alertDialog = builder.create();
                    alertDialog.show();
    				
    				break;
    				
    				
   			 
    		}
        } 
        else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
            //Toast.makeText(this, "BBB" + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();
        }
        
		return super.onContextItemSelected(item);
	 }
	
	private void createInfo() throws IllegalArgumentException, ParseException
    {
    	this.mProjcetGroupList = new ArrayList<VPProject>();
    	this.mProjectCollection = new LinkedHashMap<VPProject, List<VPProject>>();
    	
    	ApplicationInformation appInfo = new ApplicationInformation(this);
    	String path = appInfo.getDBPath();
    	VPProject_BL projectBL = new VPProject_BL(this, path);

    	mProjcetGroupList = projectBL.getAllProject();
    	
    	for(VPProject project : mProjcetGroupList)
    	{
    		mProjectList = new ArrayList<VPProject>();
    		mProjectList.add(project);
    		
    		mProjectCollection.put(project, mProjectList);
    	}
    }
	
	private void expandAll()
	{
		int count = mExpListAdapter.getGroupCount();
		for(int i = 0; i < count; i++)
		{
			mExpListView.expandGroup(i);
		}
	}
	
	private class ExpandableListProjectAdapter extends BaseExpandableListAdapter {

		private Activity myContext;
	    private Map<VPProject, List<VPProject>> myProjectCollection;
	    private List<VPProject> myProjectList;
	    
	    public ExpandableListProjectAdapter(Activity context, List<VPProject> projectList,
	            Map<VPProject, List<VPProject>> projectCollection) {
	        this.myContext = context;
	        this.myProjectCollection = projectCollection;
	        this.myProjectList = projectList;
	    }
	    
		@Override
		public Object getChild(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return this.myProjectCollection.get(myProjectList.get(groupPosition)).get(childPosition);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return childPosition;
		}
		
		public void removeChild(int groupPosition, int childPosition) {
			this.myProjectCollection.get(this.myProjectList.get(groupPosition)).remove(childPosition);
		}
		
		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			DateFormat dateFormat = DateFormat.getDateInstance();
			final VPProject project = (VPProject) getChild(groupPosition, childPosition);
	        LayoutInflater inflater = this.myContext.getLayoutInflater();
	 
	        if (convertView == null) {
	            convertView = inflater.inflate(R.layout.activity_vpproject_childitem, null);
	        }
	        
	        TextView lblProjectCode = (TextView) convertView.findViewById(R.id.expLblProjectCode);
	        TextView lblProjectDescription = (TextView) convertView.findViewById(R.id.expLblProjectDescription);
	        TextView lblProjectFromDate = (TextView) convertView.findViewById(R.id.expLblProjectFromDate);
	        TextView lblProjectToDate = (TextView) convertView.findViewById(R.id.expLblProjectToDate);
	 
	        TextView txtProjectCode = (TextView) convertView.findViewById(R.id.expTxtProjectCode);
	        TextView txtProjectDescription = (TextView) convertView.findViewById(R.id.expTxtProjectDescription);
	        TextView txtProjectFromDate = (TextView) convertView.findViewById(R.id.expTxtProjectFromDate);
	        TextView txtProjectToDate = (TextView) convertView.findViewById(R.id.expTxtProjectToDate);
	        Switch swiProjectEnableFlag = (Switch) convertView.findViewById(R.id.expSwiProjectEnableFlag);
	 
	        
	        txtProjectCode.setText(project.getVppCode());
	        txtProjectDescription.setText(project.getVppDescription());
	        
	        if (project.getVppStartDate() != null)
	        	txtProjectFromDate.setText(dateFormat.format(project.getVppStartDate()));
	        
	        if (project.getVppEndDate() != null)
	        	txtProjectToDate.setText(dateFormat.format(project.getVppEndDate()));
	        
	        if (project.getVppEnableFlag().equals("Y"))
	        	swiProjectEnableFlag.setChecked(true);
	        else
	        	swiProjectEnableFlag.setChecked(false);
	        
	        if (groupPosition % 2 == 0)
	        {
	        	convertView.setBackgroundResource(R.drawable.background_shape_gray);
	        	
	        	txtProjectCode.setTextColor(Color.BLACK);
	        	txtProjectDescription.setTextColor(Color.BLACK);
	        	txtProjectFromDate.setTextColor(Color.BLACK);
	        	txtProjectToDate.setTextColor(Color.BLACK);
	        	
	        	lblProjectCode.setTextColor(Color.BLACK);
	        	lblProjectDescription.setTextColor(Color.BLACK);
	        	lblProjectFromDate.setTextColor(Color.BLACK);
	        	lblProjectToDate.setTextColor(Color.BLACK);
	        	
	        	lblProjectCode.setHintTextColor(Color.BLACK);
	        	lblProjectDescription.setHintTextColor(Color.BLACK);
	        	lblProjectFromDate.setHintTextColor(Color.BLACK);
	        	lblProjectToDate.setHintTextColor(Color.BLACK);
	        }
	        else
	        {
	        	convertView.setBackgroundResource(R.drawable.background_shape_green);
	        	
	        	txtProjectCode.setTextColor(Color.WHITE);
	        	txtProjectDescription.setTextColor(Color.WHITE);
	        	txtProjectFromDate.setTextColor(Color.WHITE);
	        	txtProjectToDate.setTextColor(Color.WHITE);
	        	
	        	lblProjectCode.setTextColor(Color.WHITE);
	        	lblProjectDescription.setTextColor(Color.WHITE);
	        	lblProjectFromDate.setTextColor(Color.WHITE);
	        	lblProjectToDate.setTextColor(Color.WHITE);
	        	
	        	lblProjectCode.setHintTextColor(Color.WHITE);
	        	lblProjectDescription.setHintTextColor(Color.WHITE);
	        	lblProjectFromDate.setHintTextColor(Color.WHITE);
	        	lblProjectToDate.setHintTextColor(Color.WHITE);
	        }
	        
	        return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			// TODO Auto-generated method stub
			return this.myProjectCollection.get(this.myProjectList.get(groupPosition)).size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			// TODO Auto-generated method stub
			return this.myProjectList.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			// TODO Auto-generated method stub
			return this.myProjectCollection.size();
		}

		@Override
		public long getGroupId(int groupPosition) {
			// TODO Auto-generated method stub
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			VPProject projectName = (VPProject) getGroup(groupPosition);
	        if (convertView == null) {
	            LayoutInflater infalInflater = (LayoutInflater) this.myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            convertView = infalInflater.inflate(R.layout.activity_vpproject_groupitem, null);
	            convertView.setEnabled(true);
	        }
	        
	        TextView item = (TextView) convertView.findViewById(R.id.expTxtProjectGroup);
	        item.setTypeface(null, Typeface.BOLD);
	        item.setText(projectName.getVppName());
	        
	        if (groupPosition % 2 == 0)
	        {
	        	convertView.setBackgroundResource(R.drawable.background_shape_gray);
	        	item.setTextColor(Color.BLACK);
	        }
	        else
	        {
	        	convertView.setBackgroundResource(R.drawable.background_shape_green);
	        	item.setTextColor(Color.WHITE);
	        }
	        
	        return convertView;
		}

		@Override
		public boolean hasStableIds() {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return true;
		}
		
		public void filterData(String query)
		{
			myProjectCollection.clear();
			myProjectList.clear();
			
			ApplicationInformation appInfo = new ApplicationInformation(myContext.getApplicationContext());
	    	String path = appInfo.getDBPath();
	    	
	    	VPProject_BL projectBL = new VPProject_BL(myContext.getApplicationContext(), path);
	    	if(query.isEmpty())
	    	{
	    		try {
	    			myProjectList = projectBL.getAllProject();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    	}
			else
			{
				try {
					myProjectList = projectBL.getProject(query);
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
	    	
	    	List<VPProject> projectList;
	    	
	    	for(VPProject project : myProjectList)
	    	{
	    		projectList = new ArrayList<VPProject>();
				projectList.add(project);
				
				if(projectList.size() > 0)
				{
					myProjectCollection.put(project, projectList);
				}
	    	}
	    	
	    	notifyDataSetChanged();
		}

	}
}